package com.cr.admin.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.cr.admin.base.service.CaptchaService;
import com.cr.admin.system.mapper.SysMenuMapper;
import com.cr.admin.system.mapper.SysRoleMapper;
import com.cr.admin.system.mapper.SysUserMapper;
import com.cr.admin.system.pojo.dto.SysLoginParam;
import com.cr.admin.system.pojo.entity.SysUser;
import com.cr.admin.system.pojo.vo.LoginResultVO;
import com.cr.admin.system.service.ISysLoginService;
import com.cr.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class SysLoginServiceImpl implements ISysLoginService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private CaptchaService captchaService;

    @Override
    public LoginResultVO login(SysLoginParam sysLoginParam) {
        //检查验证码
        captchaService.checkCaptcha(sysLoginParam.getCaptchaKey(),sysLoginParam.getCaptcha());

        // 根据账号查询用户
        String account = sysLoginParam.getAccount();
        SysUser user = sysUserMapper.selectSysUserByUsername(account);
        // 判断账号是否不存在
        if (Objects.isNull(user)) {
            throw new ServiceException("账号或密码错误");
        }
        // 判断密码是否错误
        if (!BCrypt.checkpw(sysLoginParam.getPassword(), user.getPassword())) {
            throw new ServiceException("账号或密码错误");
        }
        // 判断账号是否被停用
        if (Objects.nonNull(user.getStatus()) && user.getStatus() == 1) {
            throw new ServiceException("账号已经被停用");
        }

        // 查询用户的角色
        List<String> roles = sysRoleMapper.selectRolesByUserId(user.getId());
        // 查询用户的权限
        List<String> perms = sysMenuMapper.selectPermsByUserId(user.getId());

        //Sa-Token 会话登录
        StpUtil.login(user.getId());


        //保存角色和权限到 Sa-Token 的session中,后期可以重复从里面拿roles和perms来使用
        StpUtil.getSession().set("roles",roles);
        StpUtil.getSession().set("perms",perms);
        StpUtil.getSession().set("nickname",user.getNickname());


        //构建登录结果VO对象
        LoginResultVO loginResultVO = new LoginResultVO();
        loginResultVO.setNickname(user.getNickname());
        loginResultVO.setAvatar(user.getAvatar());
        loginResultVO.setPerms(perms);
        loginResultVO.setToken(StpUtil.getTokenValue());


        // 返回登录结果VO对象
        return loginResultVO;
    }

}
